package com.example.demo.algorithm;

import java.util.Arrays;
import java.util.Random;

/**
 * @Author：wangsheng
 * @Description：
 * @Date：2021/12/7 22:21
 */
public class MergeSort11 {

    public static void main(String[] args) {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new Random().nextInt(100) + 0;
        }
        System.out.println("随机生成的数组为：" + Arrays.toString(arr));
        long startTime = System.currentTimeMillis();
        sort(arr);
        long endTime = System.currentTimeMillis();
        long times = endTime - startTime;
        System.out.println("排序耗时为：" + times);
        System.out.println(Arrays.toString(arr));
    }

    static void sort(int[] arr) {
        int[] temp = new int[arr.length];
        int left = 0;
        int right = arr.length - 1;
        sort(arr, left, right, temp);
    }

    static void sort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            sort(arr, left, mid, temp);
            sort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }


    }

    static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int t = left;
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t++] = arr[i++];
            } else {
                temp[t++] = arr[j++];
            }
        }
        while (i <= mid) {
            temp[t++] = arr[i++];
        }
        while (j <= right) {
            temp[t++] = arr[j++];
        }
        while (left <= right) {
            arr[left] = temp[left];
            left++;
        }
    }
}
